package ma.platform.server.core.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ma.platform.server.core.constants.TokenConstant;
import ma.platform.server.core.context.LoginUserContext;
import ma.platform.server.core.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class WxRequestFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_OK);
            R r = new R();
            r.setCode(401);
            r.setData("当前未登录");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString( r));
            return false;
        }
        if (!JWTUtil.verify(token, TokenConstant.tokenKey.getBytes())) {
            response.setStatus(HttpServletResponse.SC_OK);
            R r = new R();
            r.setCode(401);
            r.setData("无效token");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString( r));
            return false;
        }
        JWT jwt = JWTUtil.parseToken(token);
        Long id = Long.parseLong(String.valueOf(jwt.getPayload("id")));

        LoginUserContext user = LoginUserContext.getUser();
        user.setId(id);
        LoginUserContext.setUser(user);
        return true;
    }
}